/*
* @Author: yongqiang.sun
* @Date:   2018-01-15 00:40:12
* @Last Modified by:   yongqiang.sun
* @Last Modified time: 2018-01-21 00:17:03
*/
(function (window) {
    var $ = window.Zepto || window.jQuery;
    
    $(window.document).ready(function () {
        
        var shopCart = new Cart();
        // 商品数据增加事件
        $('.goods-item .counter-number__decrease').click(function () {
            var $root = $(this).closest('.goods-item');
            var val = $('.counter-input__inner', $root).val();
            if (val == 0) {
                return;
            }
            var cart = shopCart.reduceCart({
                uuid: $root.attr('data-index'),
                name: $root.attr('data-name'),
                price: $root.attr('data-price')
            });
            if (cart) {
                $('.counter-input__inner', $root).val(cart.count);
                shopCart.render();
            }
        })
        $('.goods-item .counter-number__increase').click(function () {
            var $root = $(this).closest('.goods-item');
            var cart = shopCart.addCart({
                uuid: $root.attr('data-index'),
                name: $root.attr('data-name'),
                price: $root.attr('data-price')
            })
            shopCart.render();
        })
        $('.btn-cart-pay').click(function () {
            if (shopCart.goods.length === 0) {
                return $.message().show('请选择商品');
            }

            console.log(shopCart.goods)
            $.ajax({
                type: 'POST',
                url: 'json/more.json',
                dataType: 'json',
                data: shopCart.goods,
                contentType: 'applicaton/json',
                success: function(data) {
                    console.log(data)
                },
                error: function(xhr, type) {
                    // 清空购物车
                    shopCart.clearCart()
                }
            });
        })
    })

    function Cart () {
        this.count = 0;
        this.total = 0;
        this.el = '.cart';
        this.goods = [];
        this.deleted = []; //存储删除的节点，用于清零
        this.init();
    }
    Cart.prototype = {
        init: function () {
            var self = this;
            // 购物车点击事件
            $('.cart-img').click(function () {
                var show = Number($(this).attr('data-show'));
                if (show) {
                    $('.cart-list').hide();
                    show = 0
                } else {
                    $('.cart-list').show();
                    show = 1
                }
                $(this).attr('data-show', show);
            });

            $('.cart .clear').click(function () {
                self.clearCart();
            })
            this.render();
        },
        render: function () {
            this.calc();
            var self = this;
            $('.badge-inner', $(this.el)).html(this.count);
            $('.price', $(this.el)).html(this.total);
            var host = $('.cart .cart-list .cart-list-body');
            host.html('')
            for(var i = 0; i < this.goods.length; i++) {
                var goods = this.goods[i];
                (new CartItem(goods, this)).renderTo(host);
                $('.goods .goods-item').each(function (index, el) {
                    if (goods.uuid == $(el).attr('data-index')) {
                        $('.counter-input__inner', $(el)).val(goods.count);
                        return false;
                    }
                });
            }
            for (var i = this.deleted.length - 1; i >= 0; i--) {
                var goods = this.deleted[i];
                $('.goods .goods-item').each(function (index, el) {
                    if (goods.uuid == $(el).attr('data-index')) {
                        $('.counter-input__inner', $(el)).val(0);
                        self.clear(goods);
                        return false;
                    }
                });
            }
        },
        calc: function () {
            var c = 0, t = 0;
            for (var i = 0; i < this.goods.length; i++) {
                c += this.goods[i].count;
                try {
                    t += Number.multiply(this.goods[i].price, this.goods[i].count)
                } catch (e) { }
            }

            this.total = t;
            this.count = c;
        },
        addCart: function (data) {
            var node = this.find(data.uuid)
            if (node) {
                node.count++;
            } else {
                node = $.extend(data, {count: 1});
                this.goods.push(node);
            }
            return node;
        },
        reduceCart: function (data) {
            var node = this.find(data.uuid)
            if (node && node.count > 1) {
                node.count--;
            } else if (node) {
                var index = this.findIndex(data.uuid)
                node.count--;
                this.deleted.push(this.goods.splice(index, 1)[0]);
            } else {
                return null;
            }
            return node;
        },
        find: function (uuid) {
            for (var i = this.goods.length - 1; i >= 0; i--) {
                if (this.goods[i].uuid == uuid) {
                    return this.goods[i]
                }
            }
            return null;
        },
        findIndex: function (uuid) {
            for (var i = this.goods.length - 1; i >= 0; i--) {
                if (this.goods[i].uuid == uuid) {
                    return i;
                }
            }
            return -1;
        },
        clear: function (node) {
            for (var i = this.deleted.length - 1; i >= 0; i--) {
                if (this.deleted[i].uuid == node.uuid) {
                    this.deleted.splice(i, 1)
                }
            }
        },
        clearCart: function () {
            this.goods = []
            $('.goods .goods-item').each(function (index, el) {
                $('.counter-input__inner', $(el)).val(0);
            });
            this.render();
        }
    }

    function CartItem (data, parent) {
        this.templateId = '#cart-item';
        this.template = '';
        this.data = data;
        this.parent = parent;
        this.init();
    }

    CartItem.prototype = {
        init: function () {
            this.template = $(this.templateId).html();
        },
        renderTo: function (el) {
            var self = this;
            var $html = $(Mustache.render(this.template, this.data)).find('.counter-number__increase').click(function () {
                var $root = $(this).closest('.cart-goods-item');
                var uuid = $root.attr('data-index');
                var node = self.parent.find(uuid);
                self.parent.addCart(node);
                self.parent.render();
            }).end().find('.counter-number__decrease').click(function () {
                var $root = $(this).closest('.cart-goods-item');
                var uuid = $root.attr('data-index');
                var node = self.parent.find(uuid);
                self.parent.reduceCart(node);
                self.parent.render();
            }).end().appendTo(el);
        }
    }

    Number.multiply = function (num1, num2) {
        var num1Digits = (num1.toString().split('.')[1] || '').length
        var num2Digits = (num2.toString().split('.')[1] || '').length
        var baseNum = Math.pow(10, Math.max(num1Digits, num2Digits))
        return (num1 * baseNum * num2 * baseNum) / (baseNum * baseNum)
    }

})(window)
